package de.baumann.browser.activitys;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.util.Log;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;

import de.baumann.browser.OdinApplication;
import de.baumann.browser.R;
import de.baumann.browser.base.BaseOdinActivity;
import de.baumann.browser.base.BasePresenter;
import de.baumann.browser.iview.IBaseView;
import de.baumann.browser.utils.BitmapUtil;
import de.baumann.browser.utils.FileUtil;
import de.baumann.browser.utils.UserDataKt;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * @author:
 * @date:2018/12/21 16:07
 * @discription:
 */
@RuntimePermissions
public abstract class BaseFileUploadActivity<V extends IBaseView,P extends BasePresenter<V>> extends BaseOdinActivity<V,P> {

    private BitmapUtil bitmapUtil;
    private String fileName;
    public static final int TAKEPICTURE = 1000;
    public static final int ALBUMDELECT = 1001;
    public static final int CROP = 1002;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bitmapUtil = new BitmapUtil();
    }

    public void takePicture() {
        BaseFileUploadActivityPermissionsDispatcher.takingPictureWithPermissionCheck(this);
    }

    public void albumSelect() {
        BaseFileUploadActivityPermissionsDispatcher.selectFromAlbumWithPermissionCheck(this);
    }

    @NeedsPermission({Manifest.permission.CAMERA})
    public void takingPicture() {
        fileName = System.currentTimeMillis() + ".jpg";
        Intent intent = bitmapUtil.takepictures(OdinApplication.getInstance(), fileName);
        startActivityForResult(intent, TAKEPICTURE);
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE})
    public void selectFromAlbum() {
        Intent intent = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, ALBUMDELECT);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        sheetDialog.dismiss();
        switch (requestCode) {
            case TAKEPICTURE:
                String path = FileUtil.getFilePath(fileName, FileUtil.FILE_TYPE_IMAGES);
                if (isCrop()) {
                    Intent cropIntent = bitmapUtil.photoCrop(OdinApplication.getInstance(), null,
                            TAKEPICTURE, fileName, path, getAspectX(), getAspectY(), getOutputX(), getOutputY());
                    startActivityForResult(cropIntent, CROP);
                } else {
                    compressBitmap(path);
                }
                break;
            case ALBUMDELECT:
                fileName = System.currentTimeMillis() + ".jpg";
                if (data != null) {
                    if (isCrop()) {
                        Intent intent = bitmapUtil.photoCrop(OdinApplication.getInstance(),
                                data.getData(), ALBUMDELECT, fileName, "", getAspectX(), getAspectY(), getOutputX(), getOutputY());
                        startActivityForResult(intent, CROP);
                    } else {
                        compressBitmap(data.getData());
                    }
                }
                break;
            case CROP:
                compressBitmap();
                break;
            default:
        }
    }

    private void compressBitmap() {
        String photoPath = FileUtil.getFilePath(fileName, FileUtil.FILE_TYPE_IMAGES);
        compressBitmap(photoPath);
    }

    private void compressBitmap(Uri uri) {
        compressBitmap(FileUtil.getRealFilePath(mContext, uri));
    }

    private void compressBitmap(String path) {
        Luban.with(mContext)
                .load(path)
                .ignoreBy(50)
                .setTargetDir(FileUtil.getDir(FileUtil.FILE_TYPE_IMAGES))
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        setBitmap(file.getPath());
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();

    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        BaseFileUploadActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    public boolean isCrop() {
        return false;
    }

    protected int getAspectX() {
        return 1;
    }

    protected int getAspectY() {
        return 1;
    }

    protected int getOutputX() {
        return 400;
    }

    protected int getOutputY() {
        return 400;
    }

    public abstract void setBitmap(String bitmapPath);

    public void uploadToQiNiu(String path, String token) {
        OdinApplication.getUploadManager().put(path,
                String.format("odin/app/%s/%s/%s", UserDataKt.getUserId(), String.valueOf(System.currentTimeMillis()), FileUtil.getFileName(path)),
                token,
                (key, info, response) -> {
                    if (info.isOK()) {
                        uploadSuccess(key);
                    } else {
                        uploadFailed(path);
                    }
                }, null);
    }

    int index = 0;
    LinkedHashMap<String, String> pathMap = new LinkedHashMap<>(16);

    public void uploadToQiNiu(final List<String> paths, String token) {

        for (String localPath : paths) {
            pathMap.put(localPath, localPath);
        }

        for (final String path : paths) {
            if (path.startsWith("http")) {
                index++;
                Log.d("文件批量上传", "index===" + index);
                continue;
            }

            OdinApplication.getUploadManager().put(path,
                    String.format("odin/app/%s/%s/%s", UserDataKt.getUserId(), String.valueOf(System.currentTimeMillis()), FileUtil.getFileName(path)),
                    token, (key, info, response) -> {
                        if (info.isOK()) {
                            index++;
                            pathMap.put(path, key);
                            if (index == paths.size()) {
                                uploadSuccess(pathMap);
                            }
                        } else {
                            uploadFailed(getString(R.string.Image_upload_failed));
                        }
                    }, null);
        }
    }

    protected abstract void uploadSuccess(String url);

    public void uploadSuccess(LinkedHashMap<String, String> pathMap) {

    }

    protected abstract void uploadFailed(String url);

    private BottomSheetDialog sheetDialog;

    protected void showModeSelectDialog() {
        sheetDialog = new BottomSheetDialog(mContext);
        sheetDialog.setContentView(R.layout.mode_select_dialog);
        sheetDialog.findViewById(R.id.selectCancel).setOnClickListener(view -> sheetDialog.dismiss());
        sheetDialog.findViewById(R.id.takePicture).setOnClickListener(view -> takePicture());
        sheetDialog.findViewById(R.id.albumSelect).setOnClickListener(view -> albumSelect());
        sheetDialog.show();
    }
}
